package cn.itcast.demo.task;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class HelloTask3 {

    @Autowired
    private RedissonClient redissonClient;
    int max = 2;

    @Scheduled(cron = "0/20 * * * * ?")
    public void job() throws InterruptedException {
        // 创建锁对象
        RLock lock = redissonClient.getLock("lock");

        // 调用业务
        clearOrder(lock, 1);
    }

    private void clearOrder(RLock lock, int count) {
        // 尝试获取锁
        boolean isLock = lock.tryLock();
        // 判断
        if (!isLock) {
            // 获取锁失败
            log.error("第{}层，获取 redisson 锁失败，任务结束！", count);
            return;
        }
        // 获取锁成功
        try {
            log.info("第{}层，获取 redisson 锁成功，开始清理订单。。", count);
            // 递归调用
            if(count < max) {
                clearOrder(lock, count + 1);
            }
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            lock.unlock();
            log.warn("第{}层，任务结束，释放锁！", count);
        }

    }
}
